﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;

public partial class ProposedInvoiceReport : System.Web.UI.Page, ICallbackEventHandler
{
    Dictionary<string, string> ClientRequest = null;
    Dictionary<string, string> ClientResponse = null;
    JavaScriptSerializer serializer;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsCallback)
        {
            CallBackReference();
            if (!IsPostBack)
            {
                if (SessionInfo.prop_getObj.EmployeeID == 0)
                    Response.Redirect("login.aspx");
                else
                {
                    hdnExportToExcelFilePath.Value = GlobalDefaultValues.DHTMLXExportToExcelFilePath;
                    PLMstFormMasters objRights = CommonUtil.CheckRightsForForm("2");
                    if (objRights.ViewAccess == false)
                        Response.Redirect("Login.aspx");
                    if (Request.Params.Count > 0 && Request.Params[0] == "Excel")
                    {
                        UI_ExportToExcel();
                    }
                    cboCompany.Focus();
                    UI_Filldropdowns();
                    SessionInfo.prop_getObj.PropsedInvRptSearch = new PLProposedInvoiceReportSearchCriteria();
                    SessionInfo.prop_getObj.PropsedInvRptSearch.InvStartDate = DateTime.Today.Date;
                    SessionInfo.prop_getObj.PropsedInvRptSearch.InvEndDate = DateTime.Today.Date.AddMonths(1);
                    grdResult.DataSource = new BL_Reports().BLGetProposedInvoiceReport(SessionInfo.prop_getObj.PropsedInvRptSearch);
                    grdResult.DataBind();
                }
            }
        }
    }

    protected void UI_Filldropdowns()
    {
        List<PLCompany> objCompanies = new BL_Company().BL_fnGetCompanyNameList(new PLCompany() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboCompany, objCompanies, "CompanyID", "Name");

        List<PLClient> objClients = new BL_Client().BL_fnGetClientNameList(new PLClient() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboClient, objClients, "ClientID", "ClientName");
        //CommonUtil.LoadDropdown(cboAddClient, objClients, "ClientID", "ClientName", "[Select Client]");

        List<PLContract> objContracts = new BL_Contract().BL_fnGetContractNameList(new PLContract() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboContract, objContracts, "ContractID", "ContractName");
        //CommonUtil.LoadDropdown(cboAddContract, objContracts, "ContractID", "ContractName", "[Select Contract]");

        List<PLPaymentMode> objPaymentMode = new BL_PaymentMode().BL_fnGetPaymentModeNameList(new PLPaymentMode() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboPaymentMode, objPaymentMode, "PaymentModeID", "PaymentModeName");
        txtInvoiceStartDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
        txtInvoiceEndDate.Text = DateTime.Now.AddMonths(1).ToString("dd/MM/yyyy");

    }

    // Override the Render method to ensure that this control
    // is nested in an HtmlForm server control, between a <form runat=server>
    // opening tag and a </form> closing tag.
    protected override void Render(HtmlTextWriter writer)
    {
        // Ensure that the control is nested in a server form.
        if (Page != null)
        {
            Page.VerifyRenderingInServerForm(this);
        }
        base.Render(writer);
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }



    #region callback functions
    public void CallBackReference()
    {
        string strReference = Page.ClientScript.GetCallbackEventReference(this, "args", "getResponse", "context", "ClientCallbackError", true);
        string strScript = " function UseCallback(args,context) { " + strReference + " ; } ";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", strScript, true);
    }

    public string GetCallbackResult()
    {
        System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        oSerializer.MaxJsonLength = GlobalDefaultValues.MaxJsonLength;
        return oSerializer.Serialize(ClientResponse);
    }

    public void RaiseCallbackEvent(string strEventArgument)
    {
        try
        {
            serializer = new JavaScriptSerializer();
            ClientRequest = serializer.Deserialize<Dictionary<string, string>>(strEventArgument);
            ClientResponse = new Dictionary<string, string>();
            string Track = ClientRequest["Track"];
            ClientResponse = new Dictionary<string, string>();
            ClientResponse["Track"] = Track;
            if (SessionInfo.prop_getObj.EmployeeID == 0)
            {
                ClientResponse["SessionTimeOut"] = "1";
            }
            else
            {
                ClientResponse["SessionTimeOut"] = "0";
                if (Track.Equals("GetSearchResult"))
                {
                    UI_SearchResult();
                }
                else if (Track.Equals("ViewDetails"))
                {
                    UI_ViewDetails();
                }
            }
        }
        catch (Exception ex)
        {
            CommonUtil.Elmah_SignalException(ex, this.Context, "Invoice - Method: RaiseCallbackEvent()");
        }
    }


    private void UI_SearchResult()
    {
        PLProposedInvoiceReportSearchCriteria objSearch = new PLProposedInvoiceReportSearchCriteria();
        objSearch.InvStartDate = DateTime.Today.Date;
        objSearch.InvEndDate = DateTime.Today.Date.AddMonths(1);

        PLCollection objCollection = new PLCollection();
        objSearch.CompanyIDs = ClientRequest[cboCompany.ID];
        objSearch.ClientIDs = ClientRequest[cboClient.ID];
        objSearch.ContractIDs = ClientRequest[cboContract.ID];
        objSearch.PaymentModeIDs = ClientRequest[cboPaymentMode.ID];

        objSearch.InvStartDate = CommonUtil.fnGetDateFromJSFile(ClientRequest[txtInvoiceStartDate.ID]);
        objSearch.InvEndDate = CommonUtil.fnGetDateFromJSFile(ClientRequest[txtInvoiceEndDate.ID]);
        SessionInfo.prop_getObj.PropsedInvRptSearch = objSearch;

        grdResult.DataSource = new BL_Reports().BLGetProposedInvoiceReport(objSearch);
        grdResult.DataBind();
        ClientResponse["grdResult"] = CommonUtil.GetRenderControl(grdResult);
    }

    private void UI_ViewDetails()
    {
        int intContractID = TrynParse.parseInt(ClientRequest["ContractID"]);
        grdInvoiceDetails.DataSource = new BL_Invoice().BL_fnGetInvoiceTransactions(new PLInvoice() { ContractID = intContractID });
        grdInvoiceDetails.DataBind();
        ClientResponse["grdInvoiceDetails"] = CommonUtil.GetRenderControl(grdInvoiceDetails);

        grdCollectionDetails.DataSource = new BL_Collection().BL_GetCollectionTractions(new PLCollection() { ContractID = intContractID });
        grdCollectionDetails.DataBind();
        ClientResponse["grdCollectionDetails"] = CommonUtil.GetRenderControl(grdCollectionDetails);
    }

    protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Style["display"] = "none";
            e.Row.Cells[1].Text = (e.Row.RowIndex + 1).ToString();
        }
        else if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Style["display"] = "none";
        }
    }
    #endregion

    protected void grdInvoiceDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
            e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();
    }
    protected void grdCollectionDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
            e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();
    }

    protected void UI_ExportToExcel()
    {
        if (SessionInfo.prop_getObj.PropsedInvRptSearch != null)
        {
            List<usp_GetProposedInvoiceReport_Result> objResult = new BL_Reports().BLGetProposedInvoiceReport(SessionInfo.prop_getObj.PropsedInvRptSearch);
            int intIncrementer = 0;
            var varFinalList = (from l in objResult
                                select new
                                {
                                    SrNo = intIncrementer++,
                                    Company = l.CompanyName,
                                    Client = l.ClientName,
                                    Contract = l.ContractName,
                                    ContractNo = l.ContractNo,
                                    PaymentMode = l.PaymentModeName,
                                    LastInvoiceNo = l.LastInvoiceNo,
                                    LastInvoiceDate = (l.LastInvoiceDate == null ? "" : l.LastInvoiceDate.Value.ToString("dd/MM/yyyy")),
                                    NextPaymentDay = (l.NextPaymentDay == null ? "" : l.NextPaymentDay.Value.ToString("dd/MM/yyyy")),
                                    ContractAmount = l.ContractAmount,
                                    InvoicedAmt = l.InvoicedAmt,
                                    DueAmount = l.DueAmount
                                });
            List<string> lstHeader = new List<string>() { "Sr.", "Company", "Client", "Contract","Contract #", "Last Payment Mode", "Last Invoice #", "Last Invoice Date", "Next Invoice Date", "Contract Amt", "Invoiced Amt", "Due Amt" };
            CommonUtil.ExportToExcelWithEPPlus(lstHeader, varFinalList, Response, "Proposed_Invoice_List");
        }
        else
        {
            Response.End();
        }
    }
}